package com.hjy.ware.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.hjy.common.utils.R;
import com.hjy.order.vo.OrderItemVo;
import com.hjy.order.vo.WareSkuLockVo;
import com.hjy.ware.feign.ProductFeign;
import com.hjy.ware.vo.SkuHasStockVo;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hjy.common.utils.PageUtils;
import com.hjy.common.utils.Query;

import com.hjy.ware.dao.WareSkuDao;
import com.hjy.ware.entity.WareSkuEntity;
import com.hjy.ware.service.WareSkuService;
import org.springframework.transaction.annotation.Transactional;


@Service("wareSkuService")
public class WareSkuServiceImpl extends ServiceImpl<WareSkuDao, WareSkuEntity> implements WareSkuService {

    @Autowired
    private ProductFeign productFeign;

    @Autowired
    private WareSkuDao wareSkuDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        QueryWrapper<WareSkuEntity> wrapper = new QueryWrapper<>();
        String key = (String) params.get("key");
        if (StrUtil.isNotBlank(key)) {
            wrapper.and(wareSkuEntityQueryWrapper -> {
                wareSkuEntityQueryWrapper.eq("id", key).or().like("sku_name", key);
            });
        }
        IPage<WareSkuEntity> page = this.page(
                new Query<WareSkuEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void addStock(Long skuId, Long wareId, Integer skuNum) {
        QueryWrapper<WareSkuEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("sku_id", skuId).eq("ware_id", wareId);
        Long count = baseMapper.selectCount(wrapper);
        // 远程调用, 获取 skuName
        String skuName = "";
        if (skuId != 0) {
            R info = productFeign.info(skuId);
            if (ObjectUtil.isNotNull(info)) {
                Map<String, Object> skuInfo = (Map<String, Object>) info.get("skuInfo");
                skuName = (String) skuInfo.get("skuName");
            }
        }
        if (count > 0) {
            // 修改
            UpdateWrapper<WareSkuEntity> wrapper1 = new UpdateWrapper<>();
            wrapper1.eq("ware_id", wareId).eq("sku_id", skuId);
            WareSkuEntity wareSkuEntity = new WareSkuEntity();
            wareSkuEntity.setStock(skuNum);
            wareSkuEntity.setSkuName(skuName);
            baseMapper.update(wareSkuEntity, wrapper1);
        } else {
            // 新增
            WareSkuEntity wareSkuEntity = new WareSkuEntity();
            wareSkuEntity.setStock(skuNum);
            wareSkuEntity.setSkuId(skuId);
            wareSkuEntity.setWareId(wareId);
            wareSkuEntity.setSkuName(skuName);
            baseMapper.insert(wareSkuEntity);
        }
    }

    @Override
    public List<SkuHasStockVo> hasStock(List<Long> list) {
        // 首先获取所有的
        List<WareSkuEntity> list1 = this.list(new QueryWrapper<WareSkuEntity>().in("sku_id", list));
        List<SkuHasStockVo> skuHasStockVos = null;
        skuHasStockVos = list1.stream().map(wareSkuEntity -> {
            SkuHasStockVo skuHasStockVo = new SkuHasStockVo();
            skuHasStockVo.setSkuId(wareSkuEntity.getSkuId());
            skuHasStockVo.setHasStock((wareSkuEntity.getStock() - wareSkuEntity.getStockLocked()) > 0);
            return skuHasStockVo;
        }).collect(Collectors.toList());
        return skuHasStockVos;
    }

    @Transactional
    @Override
    public Boolean orderLockStock(WareSkuLockVo vo) {
        List<OrderItemVo> locks = vo.getLocks();

        //找到每个商品在哪个仓库都有库存
        List<SkuWareHasStock> collect = locks.stream().map(item -> {
            SkuWareHasStock skuWareHasStock = new SkuWareHasStock();
            skuWareHasStock.setSkuId(item.getSkuId());
            skuWareHasStock.setNum(item.getCount());
            List<Long> wareIds = wareSkuDao.listWareIdHasSkuStock(item.getSkuId());
            skuWareHasStock.setWareId(wareIds);
            return skuWareHasStock;
        }).collect(Collectors.toList());


        // 锁定库存
        for (SkuWareHasStock skuWareHasStock : collect) {
            Boolean allLock = false;
            List<Long> wareIds = skuWareHasStock.getWareId();
            if (CollUtil.isEmpty(wareIds)) {
                throw new RuntimeException(skuWareHasStock.getSkuId() + "商品无库存");
            }
            for (Long wareId : wareIds) {
                // 对这个仓库锁定库存
                Long count = wareSkuDao.lockSkuStock(skuWareHasStock.getSkuId(), wareId, skuWareHasStock.getNum());
                if (count > 0) {
                    // 成功锁定
                    allLock = true;
                    break;
                }
            }
            if (!allLock) {
                throw new RuntimeException(skuWareHasStock.getSkuId() + "商品无库存");
            }
        }

        return true;
    }


    @Data
    public static class SkuWareHasStock {
        private Long skuId;
        private Integer num;
        private List<Long> wareId;
    }

}